<?php

namespace app\admin\controller;

use app\common\controller\AdminBase;
use think\App;
use think\exception\ValidateException;
use think\facade\Log;
use util\Excel;
use util\Token;
use util\Upload;
use think\cache\driver\Redis;

/**
 * Advertising控制器
 */
class Advertisingapi extends AdminBase
{

    protected $model = null;
    protected $advplat_model = null;

    protected $validate = null;

    protected $relationSearch = false;

    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->model = new \app\admin\model\Advertisingapi();
        $this->advplat_model = new \app\admin\model\Advplat();

        $this->validate = \app\admin\validate\Advertising::class;
    }


    /**
     * 列表
     */
    public function index()
    {
        $token = $this->request->header('token');
        // 查询用户id
        $adminId = Token::userId($token);
        $is_superadmin = Token::is_superadmin($token);

        list($limit, $where, $sortArr) = $this->buildTableParames();
        // halt($where);
        $where = array();
        if (!$is_superadmin) {
            $where[] = ['a.admin_id',  '=', $adminId];
        }
        $where[] = ['b.status', '=', 'normal'];
        $where[] = ['a.spend', '>', 0.001];
        $list = table('advertisingapi')
            ->field("a.id as ids,b.account as account_id,a.date_start,SUM(`spend`) as spend,b.id,b.adv_id,b.site_id")
            ->alias('a')
            ->join('qu_advplat b', 'b.id = a.advplat_id', 'left')
            ->where($where)
            ->group('a.advplat_id,a.date_start')
            ->limit(100000)
            ->order('a.date_start desc,a.spend desc')
            ->paginate($limit);

        $redis = new Redis();
        $lists = $list->items();
        foreach ($lists as $k => $v) {
            $site = $redis->get('site_name'.$v['site_id']);
            if (empty($site)) {
                $site = table('site')
                ->where('id', $v['site_id'])
                ->find();
                $redis->set('site_name'.$v['site_id'], $site, 60*60);
            }  
            if (!empty($site)) {
                $lists[$k]['site_name'] = $site['site_name'];
            } else {
                $lists[$k]['site_name'] = '暂无';
            }
            //广告平台
            $advplatform = $redis->get('adv_name'.$v['adv_id']);
            if (empty($advplatform)) {
                $advplatform = table('advplatform')
                ->where('id', $v['adv_id'])
                ->find();
                $redis->set('adv_name'.$v['adv_id'], $advplatform, 60*60);
            }
            if (!empty($advplatform)) {
                $lists[$k]['adv_name'] = $advplatform['title'];
            } else {
                $lists[$k]['adv_name'] = '暂无';
            }

            $lists[$k]['hasChildren'] = true;
            $lists[$k]['spend'] = number_format((float)$v['spend']*1, 2, '.', '');
        }

        $data = [
            'code' => 1,
            'msg' => '',
            'count' => $list->total(),
            'data' => $lists,
        ];
        return json($data);
    }

    
    //通过批次号查询相关信息
    public function  get_adv_id()
    {
        $post = $this->request->post();
        if(empty($post['id']) || empty($post['date_start'])){
            return error('参数错误请刷新再试');
        }
        $rst = table('advertisingapi')
            ->where(['advplat_id' => $post['id']])
            ->where(['date_start' => $post['date_start']])
            ->select()
            ->toarray();
        foreach ($rst as $key => $value) {
            if(!empty($value['error'])){
                $rst[$key]['spend'] = $value['error'];
            }
            $rst[$key]['ids'] = $value['id'].'1';
        }
        return success('ok', $rst);
    }

    /**
     * 添加
     */
    public function add()
    {
        $post = $this->request->post();

        try {
            $token = $this->request->header('token');
            // 查询用户id
            $adminId = Token::userId($token);
            // halt($post);
            $post['admin_id'] = !empty($post['admin_id']) ? $post['admin_id'] : $adminId;
            // $advplat = table('advplat')->where(['id' => $post['plat_account']])->find();
            // $post['plat'] = $advplat['adv_id'];
            $this->validate && validate($this->validate)->check($post);
            $post['create_time'] = date('Y-m-d', $post['create_times']);
            unset($post['create_times']);
            $result = $this->model->save($post);
            if ($result) {
                return success('添加成功！');
            }
            return error('添加失败');
        } catch (ValidateException $e) {

            return error($e->getError());
        } catch (\Exception $e) {
            return error('添加失败:' . $e->getMessage());
        }
    }
    /**
     * 修改
     *
     */
    public function edit()
    {
        $id = input('id');
        $row = $this->model->find($id);
        if (empty($row)) {
            return error('数据不存在');
        }
        if ($this->request->isPost()) {
            $post = $this->request->post();
            try {
                $this->validate && validate($this->validate)->scene('edit')->check($post);
                $post['create_time'] = date('Y-m-d', $post['create_times']);
                // $advplat = table('advplat')->where(['id' => $post['plat_account']])->find();
                // $post['plat'] = $advplat['adv_id'];
                unset($post['create_times']);
                $result = $row->save($post);
                if ($result) {
                    return success('保存成功！');
                }
                return error('保存失败');
            } catch (ValidateException $e) {
                return error($e->getError());
            } catch (\Exception $e) {
                Log::error("--------:" . $e);
                return error('保存失败');
            }
        }
        return success('ok', $row);
    }

    /**
     * 查找
     */
    public function find()
    {
        $id = input('id');
        $row = $this->model->find($id);
        if (empty($row)) {
            return error('数据不存在');
        }
        return success('ok', $row);
    }


    /**
     * 上传文件
     */
    public function uploads()
    {
        $file = $this->request->file('file');
        // try {
        $upload = new Upload();
        $res = $upload->upload($file);
        if ($res['url']) {
            // return success('ok', $res['url']);
            $return = $this->import_cost($res['url']);
            return success('ok', $return);
        } else {
            return error($res['msg']);
        }
        // } catch (\Exception $e) {
        //     Log::error("---ajax---upload--error:" . $e);
        // }
        return error('上传文件失败');
    }

    //导入花费
    public function  import_cost($url)
    {
        $url_arr = explode('storage/', $url);
        $data = Excel::import('storage/' . $url_arr[1]);
        unset($data[1]);
        foreach ($data as  $value) {
            //处理时间
            $date = date_parse_from_format('Y-m-d', $value[4]);
            $time = date('Y-m-d H:i:s', mktime(0, 0, 0, $date['month'], $date['day'], $date['year']));
            //查询平台
            $advplatform = table('advplatform')->where(['title' => $value[2]])->find();
            if (empty($advplatform)) {
                $query_field = 'title';
                $advplatform_where[] = [$query_field, 'LIKE', "%' .$value[2]. '%"];
                $advplatform = table('advplatform')->where($advplatform_where)->find();
            }
            //查询账号id和adminid
            $advplat = table('advplat')->where('find_in_set(' . $value[0] . ',account)')->find();
            if (empty($advplat)) {
                $advplat = table('advplat')->where(['account' => $value[0]])->order(['id' => 'desc'])->find();
            }
            if (empty($advplat)) {
                $advplat = table('advplat')->where('account', 'LIKE', '%' . $value[0] . '%')->order(['id' => 'desc'])->find();
            }
            $arr_insert = [
                'cost' => isset($value[3]) ? $value[3] : 0,
                'plat' => isset($advplatform['id']) ?  $advplatform['id'] : 0,
                'plat_account' => isset($advplat['id']) ?  $advplat['id'] : 0,
                'admin_id' => isset($advplat['admin_ids']) ?  $advplat['admin_ids'] : 0,
                'create_time' => $time ?  $time : 0,
            ];
            table('advertising')->insert($arr_insert);
        }
        return $url;
    }
}
